<?php
/**
 * 通用内容列表组件
 * 用于展示各种类型的内容列表，支持网格布局、筛选和分页功能
 */

// 获取调用此组件的当前碎片名称
$currentFragment = basename(__FILE__, '.php');

// 确定要使用的配置键
// 1. 首先检查是否通过参数传递了配置键
$configKey = isset($configKey) ? $configKey : '';

// 2. 如果没有传递配置键，尝试从当前上下文获取
if (empty($configKey) && !empty($fragment)) {
    $configKey = $fragment;
}

// 3. 默认使用组件名称作为配置键
if (empty($configKey)) {
    $configKey = $currentFragment;
}

// 从页面配置获取内容列表组件配置，使用默认值作为后备
$data = array_merge([
    'section_id' => 'content-list',
    'section_pretitle' => '内容列表',
    'section_title' => '内容列表',
    'section_subtitle' => '查看所有内容，发现更多相关内容',
    'layout' => 'grid', // grid, list, masonry
    'columns' => '3',
    'filter_type' => 'category',
    'bg_color' => 'white',
    'card_style' => 'modern',
    'hover_effect' => 'scale',
    'show_filter' => true,
    'show_pagination' => true,
    'items_per_page' => 9,
    'items' => [],
    'item_type' => 'item', // 用于定制显示文本
    'empty_text' => '未找到结果',
    'empty_subtext' => '当前筛选条件下没有找到内容，请尝试其他筛选条件。',
    'py' => '16',
    'container_padding_x' => 'px-4 sm:px-6 lg:px-8',
    'title_margin_bottom' => '12',
    'filter_margin_bottom' => '10',
    'grid_gap' => '8'
], $pageConfig['components'][$configKey] ?? []);

// 根据列数设置网格类
$gridClasses = [
    '1' => 'grid-cols-1',
    '2' => 'grid-cols-1 md:grid-cols-2',
    '3' => 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
    '4' => 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4'
];
$gridClass = $gridClasses[$data['columns']] ?? $gridClasses['3'];

// 设置背景颜色类
$bgColorClasses = [
    'white' => 'bg-white',
    'gray' => 'bg-gray-50',
    'primary' => 'bg-primary/5',
    'secondary' => 'bg-secondary/5'
];

// 获取所有类别用于筛选
$categories = ['all' => '全部'];
foreach ($data['items'] as $item) {
    if (!empty($item[$data['filter_type']]) && !isset($categories[$item[$data['filter_type']]])) {
        // 尝试获取类别显示名称，如果没有则使用类别值
        $categories[$item[$data['filter_type']]] = $item[$data['filter_type'] . '_name'] ?? $item[$data['filter_type']];
    }
}

// 处理筛选
$selectedFilter = isset($_GET[$data['filter_type']]) ? $_GET[$data['filter_type']] : 'all';
$filteredItems = $data['items'];
if ($selectedFilter !== 'all') {
    $filteredItems = array_filter($data['items'], function ($item) use ($selectedFilter, $data) {
        return $item[$data['filter_type']] === $selectedFilter;
    });
}

// 处理分页
$totalItemsCount = count($filteredItems);
$totalPages = ceil($totalItemsCount / $data['items_per_page']);
$currentPage = isset($_GET['page']) ? max(1, min(intval($_GET['page']), $totalPages)) : 1;
$offset = ($currentPage - 1) * $data['items_per_page'];
$pagedItems = array_slice($filteredItems, $offset, $data['items_per_page']);

// 构建查询参数
$searchQuery = isset($_GET['s']) ? 's=' . htmlspecialchars($_GET['s']) : '';

// 开始输出组件
?>

<section id="<?= htmlspecialchars($data['section_id']); ?>" class="py-<?= $data['py']; ?>">
    <div class="container mx-auto <?= $data['container_padding_x']; ?>">
        <!-- 标题部分 -->
        <div class="text-center mb-<?= $data['title_margin_bottom']; ?>">
            <?php if (!empty($data['section_pretitle'])): ?>
                <span class="inline-block px-3 py-1 text-sm font-semibold text-primary bg-primary/10 rounded-full mb-4">
                    <?= htmlspecialchars($data['section_pretitle']); ?>
                </span>
            <?php endif; ?>

            <h2 class="text-3xl md:text-4xl font-bold mb-4 text-gray-900">
                <?= htmlspecialchars($data['section_title']); ?>
            </h2>

            <?php if (!empty($data['section_subtitle'])): ?>
                <p class="text-lg text-gray-600 max-w-3xl mx-auto">
                    <?= htmlspecialchars($data['section_subtitle']); ?>
                </p>
            <?php endif; ?>
        </div>

        <!-- 筛选器 -->
        <?php if ($data['show_filter'] && count($categories) > 1): ?>
            <div class="flex flex-wrap justify-center gap-2 mb-<?= $data['filter_margin_bottom']; ?>">
                <?php foreach ($categories as $key => $label): ?>
                    <a href="?s=<?= htmlspecialchars($_GET['s'] ?? ''); ?>&<?= $data['filter_type']; ?>=<?= $key; ?>
                       " class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-300
                          <?= $selectedFilter === $key
                                ? 'bg-primary text-white'
                                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'; ?>">
                        <?= $label; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- 内容列表 -->
        <div class="grid <?php echo $gridClass; ?> gap-<?= $data['grid_gap']; ?>">
            <?php if (!empty($pagedItems)): ?>
                <?php foreach ($pagedItems as $item): ?>
                    <!-- 通用卡片结构 -->
                    <div class="rounded-xl overflow-hidden shadow-lg transition-all duration-300 transform hover:-translate-y-2 hover:shadow-xl">
                        <!-- 图片部分 (如果有) -->
                        <?php if (!empty($item['image'])): ?>
                            <div class="relative aspect-video overflow-hidden bg-gray-100">
                                <img
                                    src="<?= htmlspecialchars($item['image']); ?>
                                    alt="<?= htmlspecialchars($item['title'] ?? $item['name'] ?? ''); ?>
                                    class="w-full h-full object-cover transition-transform duration-500 hover:scale-110">
                                 
                                <!-- 标签 (如果有) -->
                        <?php if (!empty($item[$data['filter_type']])): ?>
                            <div class="absolute top-4 left-4">
                                <span class="inline-block px-3 py-1 bg-white/90 backdrop-blur-sm text-primary text-xs font-medium rounded-full">
                                    <?= $item[$data['filter_type'] . '_name'] ?? $item[$data['filter_type']]; ?>
                                </span>
                            </div>
                        <?php endif; ?>
                                
                                <!-- 其他标签 (如折扣等，如果有) -->
                                <?php if (!empty($item['discount']) && $item['discount'] !== '0%'): ?>
                                    <div class="absolute top-4 right-4">
                                        <span class="inline-block px-3 py-1 bg-secondary text-white text-xs font-medium rounded-full">
                                            省 <?php echo htmlspecialchars($item['discount']); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <!-- 内容部分 -->
                        <div class="p-6">
                            <!-- 评分 (如果有) -->
                            <?php if (!empty($item['rating'])): ?>
                                <div class="flex items-center mb-3">
                                    <?php echo generateStarRating($item['rating']); ?>
                                    <span class="text-sm font-medium text-gray-600 ml-2">
                                        <?php echo htmlspecialchars($item['rating']); ?>
                                        <?php if (!empty($item['rating_count'])): ?>
                                            <span class="text-gray-400 text-xs">(<?php echo htmlspecialchars($item['rating_count']); ?>)</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                            <?php endif; ?>

                            <!-- 标题和副标题 -->
                            <h3 class="text-xl font-bold mb-1 text-gray-900 hover:text-primary transition-colors duration-300">
                                <a href="<?php echo htmlspecialchars($item['url'] ?? '#'); ?>">
                                    <?php echo htmlspecialchars($item['title'] ?? $item['name'] ?? ''); ?>
                                </a>
                            </h3>
                            
                            <!-- 描述/副标题 -->
                            <?php if (!empty($item['subtitle']) || !empty($item['description']) || !empty($item['excerpt'])): ?>
                                <p class="text-gray-600 mb-4 text-sm line-clamp-2">
                                    <?php echo htmlspecialchars($item['subtitle'] ?? $item['description'] ?? $item['excerpt'] ?? ''); ?>
                                </p>
                            <?php endif; ?>

                            <!-- 标签 -->
                            <?php if (!empty($item['tags']) && is_array($item['tags'])): ?>
                                <div class="flex flex-wrap gap-2 mb-4">
                                <?php foreach (array_slice($item['tags'], 0, 3) as $tag): ?>
                                    <span class="inline-block px-2 py-1 bg-gray-100 text-gray-700 text-xs font-medium rounded-md">
                                        <?php echo htmlspecialchars($tag); ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>

                            <!-- 底部信息 -->
                            <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
                                <!-- 左侧信息 (如作者、开发商等) -->
                                <div class="text-sm text-gray-500">
                                    <?php 
                                        $leftInfo = '';
                                        if (!empty($item['author'])) {
                                            $leftInfo = is_array($item['author']) ? ($item['author']['name'] ?? '') : $item['author'];
                                        } elseif (!empty($item['developer'])) {
                                            $leftInfo = $item['developer'];
                                        } elseif (!empty($item['date'])) {
                                            $leftInfo = $item['date'];
                                        }
                                        echo htmlspecialchars($leftInfo);
                                    ?>
                                </div>
                                
                                <!-- 右侧信息 (如价格、阅读时间等) -->
                                <div class="font-bold text-gray-900">
                                    <?php 
                                        $rightInfo = '';
                                        if (!empty($item['discounted_price'])) {
                                            $rightInfo = $item['discounted_price'];
                                            if (!empty($item['discount']) && $item['discount'] !== '0%' && !empty($item['price'])) {
                                                $rightInfo .= ' <span class="ml-2 text-sm font-normal text-gray-400 line-through">' . $item['price'] . '</span>';
                                            }
                                        } elseif (!empty($item['price'])) {
                                            $rightInfo = $item['price'];
                                        } elseif (!empty($item['read_time'])) {
                                            $rightInfo = $item['read_time'];
                                        }
                                        echo $rightInfo;
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-span-full text-center py-16">
                    <div class="w-24 h-24 mx-auto mb-4 text-gray-300">
                        <i class="fa fa-search text-6xl"></i>
                    </div>
                    <h3 class="text-xl font-bold mb-2 text-gray-900"><?= $data['empty_text']; ?></h3>
                    <p class="text-gray-600"><?= $data['empty_subtext']; ?></p>
                    <a href="?s=<?= htmlspecialchars($_GET['s'] ?? ''); ?>&<?= $data['filter_type']; ?>=all" class="inline-block mt-4 px-6 py-2 bg-primary text-white font-medium rounded-lg transition-all duration-300 hover:bg-primary/90">
                        查看全部
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</section>